package com.company.string;

/**
 * @author jrue
 * @description https://leetcode-cn.com/problems/longest-common-prefix/
 * @date 2019/11/16 10:35
 * 编写一个函数来查找字符串数组中的最长公共前缀。
 *
 * 如果不存在公共前缀，返回空字符串 ""。
 */
public class LongestCommonPrefix {

    public static void main(String[] args) {
        System.out.println(longestCommonPrefix(new String[]{"c","c"}));
    }

    // 1ms over 93.57%
    // 37.5m over 77.13%
    public static String longestCommonPrefix02(String[] strs) {
        if (strs.length == 0 ) return "";
        int len = 0;
        for (int i = 0; i < strs[0].length(); i++) {
            char c = strs[0].charAt(i);
            boolean flag = false;
            for (int j = 0; j < strs.length; j++) {
                if (i >= strs[j].length()) {
                    flag = true;break;
                }
                else if (strs[j].charAt(i) != c) {
                    flag = true;break;
                }
            }
            if (!flag) {
                len++;
            } else {
                break;
            }
        }
        return strs[0].substring(0,len);
    }

    // 2ms over 58.73%
    // 38m over 64.74%
    public static String longestCommonPrefix(String[] strs) {
        if (strs.length == 0) return "";
        if (strs.length == 1) return strs[0];
        String s = strs[0];
        for (int i = 1; i < strs.length; i++) {

            int j = 0;
            // point
            for (; j < strs[i].length() && j < s.length(); j++) {
                if (s.charAt(j) != strs[i].charAt(j)) break;
            }

             s = s.substring(0,j);
            if (s.equals("")) return "";
        }

        return s;
    }

}
